/**
 * 入口
 * intent:android.intent.action.WZ_PRINT_IMAGE
 * StringExtra1 
 *    key:       file_path
 *    Content:   图片路径
 * StringExtra2 
 *    key:       display_mode 
 *    Content:   "mode_default"  (不启动窗口直接按照默认参数打印)
 *               "mode_standard" (正常启动窗口)
 * test:
 * adb shell am start -a android.intent.action.WZ_PRINT_IMAGE -e file_path "/sdcard/tmp.jpg" -e display_mode "mode_standard"
 * 
 */

package com.wizhong.os.printimage;

import java.io.IOException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.Spinner;

import com.itextpdf.text.DocumentException;
import com.wizhong.os.printimage.service.ImageService;

public class MainActivity extends Activity {
	private final String LOG_TAG = "MainActivity";
	private ImageView test_imageview;
	private boolean isMatchFrame = false;
	private boolean isRotate = false;
	private Context mContext = this;
	private boolean DEBUG = true;
	private boolean isPhoto = false;
	Bitmap mBitmap;
	PaperSize mPaperSize = PaperSize.PAERSIZE_4_INCH;
	
	private Spinner printer_spinner;
	private Spinner papersize_spinner;
	private Spinner print_quality_spinner;
	private Spinner papertype_spinner;

	String pdfPath = "/sdcard/tmp2.pdf";

	private CheckBox match_frame_checkbox;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* 获取启动参数 */
		Intent intent = getIntent();
		String mPath = intent.getStringExtra("file_path");
		String mMode = intent.getStringExtra("display_mode");
		if(DEBUG) Log.i(LOG_TAG, "file_path = " + mPath + ";\n" + "display_mode = " + mMode);

		try {
			/* TODO:判断是否为系统uid 参数是否为空 文件不存在 没有读权限　路径不是图片 统统返回 */
			
			/* 1.获取上次的配置参数 */ 
			getPreferences();
			
			/* 2.判断合法性 */
			if (mPath == null) {
				mBitmap = BitmapFactory.decodeStream(getResources().openRawResource(R.drawable.babaosys));
			} else {
				ImageService.isPicture(mPath);
				mBitmap = BitmapFactory.decodeFile(mPath);
			}
			
			/* 3.启动直接打印 */
			if (mMode != null && mMode.equals("Quick")) {
				URL url1 = null, url2 = null, url3 = null;
				new PrintFilesTask().execute(url1, url2, url3);
				/* 退出程序　 */
				this.finish();
				// setContentView(R.layout.activity_none);
			}

			/* 4.启动正常界面 */
			setContentView(R.layout.copy_of_activity_main);
			initUI();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
	}

	private void getPreferences() {
		/* TODO:读到上次保存的配置参数 */

	}

	private void initUI() {
		/* head 相关 */
		printer_spinner = (Spinner) this.findViewById(R.id.pritner_select_spinner);
		papersize_spinner = (Spinner) this.findViewById(R.id.papersize_select_spinner);
		/* PaperType */
		papertype_spinner = (Spinner) this.findViewById(R.id.papertype_spinner);
		papertype_spinner
		.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				switch (arg2) {
				case 0: /*normally*/
					break;
				case 1: /*normally*/
					isPhoto = true;
					break;
				default:
					break;
				}
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		/* Print Quality */
		print_quality_spinner = (Spinner) this.findViewById(R.id.quality_select_spinner);
		ArrayAdapter<String> printer_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.printers));
		printer_spinner.setAdapter(printer_adapter);
		ArrayAdapter<String> papersize_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.paper_size));
		/* PaperSize */
		papersize_spinner.setAdapter(papersize_adapter);
		ArrayAdapter<String> print_quality_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.print_quality));
		papersize_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				switch (arg2) {
				case 0: /*4"x6"*/
					mPaperSize = PaperSize.PAERSIZE_4_INCH;
					break;
				case 1: /*5"x7"*/
					mPaperSize = PaperSize.PAERSIZE_5_INCH;
					break;
				case 2: /*6"x8"*/
					mPaperSize = PaperSize.PAERSIZE_6_INCH;
					break;
				case 3: /*8"x10"*/
					mPaperSize = PaperSize.PAERSIZE_8_INCH;
					break;
				default:
					break;
				}
				updateShowImage();
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		
		print_quality_spinner.setAdapter(print_quality_adapter);
		ArrayAdapter<String> papertype_adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.paper_type));
		papertype_spinner.setAdapter(papertype_adapter);
		/* 选项　相关 */

		/* 照片预览相关　相关 */
		try {
			preImageHandle();
		} catch (Exception e) {
			e.printStackTrace();
			this.finish();
		}
		test_imageview = (ImageView) this.findViewById(R.id.test_imageview);
		test_imageview.setImageBitmap(mBitmap);

		/* 适应边框打印　相关 */
		isMatchFrame = false;
		match_frame_checkbox = (CheckBox) this
				.findViewById(R.id.match_frame_checkbox);
		match_frame_checkbox.setChecked(isMatchFrame);
		match_frame_checkbox
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton arg0,
							boolean arg1) {
						isMatchFrame = arg1 ? true : false;
						updateShowImage();
					}
				});
		updateShowImage();
	}

	/**
	 * 图片显示预处理
	 */
	private void preImageHandle() throws Exception {
		/* 1.旋转-90 */
		if (mBitmap.getWidth() < mBitmap.getHeight()) {
			mBitmap = ImageService.rotateBitmap(mBitmap, -90);
			isRotate = true;
		} else {
			isRotate = false;
		}
	}

	/**
	 * 更新显示图片
	 */
	private void updateShowImage() {
		test_imageview.getLayoutParams().width = mPaperSize.getHeight()/2;
		test_imageview.getLayoutParams().height = mPaperSize.getWidth()/2;
		if (isMatchFrame) {
			/* 按照宽 */
			test_imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
		} else {
			/* 按照高 */
			test_imageview.setScaleType(ImageView.ScaleType.FIT_CENTER);
		}
	}

	/**
	 * 打印按钮调用的方法
	 * @param v
	 */
	public void doPrintPhoto(View v) {
		URL url1 = null, url2 = null, url3 = null;
		new PrintFilesTask().execute(url1, url2, url3);
	}

	private class PrintFilesTask extends AsyncTask<URL, Integer, Long> {
		protected Long doInBackground(URL... urls) {
			int count = urls.length;
			long totalSize = 0;
			try {
				/* 1.image to PDF (由于要传递的都是横向的所以isRotate始终为true) */
				ImageService.imageToPDF(mBitmap, pdfPath, false,
						!isRotate, mPaperSize.getWidth(),
						mPaperSize.getHeight());

				/* 2.print */
				ImageService.doPrint(mContext, isPhoto, pdfPath, mPaperSize);

			} catch (DocumentException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return totalSize;
		}

		protected void onProgressUpdate(Integer... progress) {
		}

		protected void onPostExecute(Long result) {
		}
	}
	
	public void closeActivity(View v) {
		this.finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
